<template>
  <div class="app-container">
    <!-- 岗位查询表单 -->
    <el-form :model="queryParams" ref="queryForm" :inline="true" label-width="68px">
      <el-form-item label="岗位编码" prop="postCode">
        <el-input
          v-model="queryParams.postCode"
          style="width: 240px"
          placeholder="请输入岗位编码"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="岗位名称" prop="postName">
        <el-input
          v-model="queryParams.postName"
          placeholder="请输入岗位名称"
          clearable
          @keyup.enter="handleQuery"
          style="width: 240px"
        />
      </el-form-item>
      <el-form-item label="状态" prop="status">
        <el-select v-model="queryParams.status" placeholder="岗位状态" clearable style="width: 240px">
          <el-option v-for="item in dictItem.type.sys_normal_disable" :key="item.value" :label="item.label" :value="item.value" />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="handleQuery">搜索</el-button>
        <el-button @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>
    <!-- 操作按钮组 -->
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain @click="handleAdd" v-p="['system:post:add']">新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          :disabled="ids.length > 1 || ids.length === 0"
          @click="handleUpdate"
          v-p="['system:post:edit']"
        >
          修改
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="danger" plain :disabled="ids.length === 0" @click="handleDelete" v-p="['system:post:remove']">
          删除
        </el-button>
      </el-col>
      <!-- <el-col :span="1.5">
        <el-button type="warning" plain @click="handleExport"
          v-p="['system:post:export']">导出</el-button>
      </el-col> -->
    </el-row>
    <!-- 岗位列表表格 -->
    <el-table v-loading="loading" :data="postList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="岗位编号" align="center" prop="postId" />
      <el-table-column label="岗位编码" align="center" prop="postCode" />
      <el-table-column label="岗位名称" align="center" prop="postName" />
      <el-table-column label="岗位排序" align="center" prop="postSort" />
      <el-table-column label="状态" align="center" prop="status">
        <template v-slot="scope">
          <el-tag type="" v-if="scope.row.status === '0'">正常</el-tag>
          <el-tag type="danger" v-else>停用</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="创建时间" align="center" prop="createTime" width="180">
        <template v-slot="scope">
          <span>{{ scope.row.createTime }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template v-slot="scope">
          <el-button type="primary" link @click="handleUpdate(scope.row)" v-p="['system:post:edit']">修改</el-button>
          <el-button type="primary" link @click="handleDelete(scope.row)" v-p="['system:post:remove']">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页组件 -->
    <Pagination
      :total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @update:page="handlePageChange"
      @update:limit="handlePageSizeChange"
    />
    <!-- 弹窗 -->
    <el-dialog :title="title" v-model="open" width="500px" append-to-body>
      <el-form ref="formRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="岗位名称" prop="postName">
          <el-input v-model="form.postName" placeholder="请输入岗位名称" />
        </el-form-item>
        <el-form-item label="岗位编码" prop="postCode">
          <el-input v-model="form.postCode" placeholder="请输入编码名称" />
        </el-form-item>
        <el-form-item label="岗位顺序" prop="postSort">
          <el-input-number v-model="form.postSort" controls-position="right" :min="0" />
        </el-form-item>
        <el-form-item label="岗位状态" prop="status">
          <el-radio-group v-model="form.status">
            <el-radio v-for="item in dictItem.type.sys_normal_disable" :key="item.value" :label="item.value">
              {{ item.label }}
            </el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" type="textarea" placeholder="请输入内容" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import type { FormRules, FormInstance } from "element-plus";
import type { PostItem } from "@/typings";
import { addPostApi, delPostApi, getPostInfoApi, getPostListApi, updatePostApi } from "@/api";
import { onMounted, reactive, ref } from "vue";
import { ElMessage, ElMessageBox } from "element-plus";
import Pagination from "@/components/pagination/Pagination.vue";

/**
 * 定义总页数
 */
const total = ref(0);
/**
 * 处理页码变化
 */
const handlePageChange = (page: number) => {
  queryParams.pageNum = page;
  getPostList();
};
/**
 * 处理每页条数变化
 */
const handlePageSizeChange = (size: number) => {
  queryParams.pageSize = size;
  getPostList();
};
/**
 * 定义岗位列表数据
 */
const postList = ref<PostItem[]>([]);
/**
 * 定义加载状态
 */
const loading = ref(false);
/**
 * 查询表单
 */
const queryForm = ref<FormInstance>();
/**
 * 查询参数
 */
const queryParams = reactive({
  postCode: "",
  postName: "",
  status: "",
  pageNum: 1,
  pageSize: 10
});
/**
 * 查询岗位列表
 */
const handleQuery = () => {
  getPostList();
};

// 状态
const dictItem = {
  type: {
    sys_normal_disable: [
      { value: "0", label: "正常" },
      { value: "1", label: "停用" }
    ],
    sys_show_hide: [
      { value: "0", label: "显示" },
      { value: "1", label: "隐藏" }
    ]
  }
};

/**
 * 新增岗位
 */
const handleAdd = () => {
  title.value = "新增岗位";
  open.value = true;
};

/**
 * 修改岗位
 */
const handleUpdate = async (row: PostItem | any) => {
  resetQuery();
  try {
    title.value = "修改岗位";
    const postId = row.postId || ids.value;
    const res = await getPostInfoApi(postId);
    if (res.code === 200) {
      Object.assign(form, res.data);
    } else {
      ElMessage.error(res.message);
    }
  } catch (error) {
    console.error(error);
  }
  open.value = true;
};

/**
 * 删除岗位
 */
const handleDelete = (row: PostItem | any) => {
  try {
    if (ids.value.length > 0) {
      row.postId = ids.value.join(",");
    }
    ElMessageBox.confirm("确定删除所勾选的岗位吗？删除之后数据将无法恢复", "系统提示", {
      type: "warning"
    }).then(async () => {
      const res = await delPostApi(row.postId);
      if (res.code === 200) {
        ElMessage.success("删除成功");
        getPostList();
      } else {
        ElMessage.error(res.message);
      }
    });
  } catch (error) {
    ElMessage.error("delete Data error");
  }
};

/**
 * 导出岗位
 */
// const handleExport = () => {};

/**
 * 多选岗位ID数组
 */
const ids = ref<number[]>([]);
/**
 * 处理表格选中行变化
 */
const handleSelectionChange = (row: PostItem[]) => {
  ids.value = row.map((item: PostItem) => item.postId);
};

/**
 * 重置查询表单
 */
const resetQuery = () => {
  queryForm.value?.resetFields();
  getPostList();
};

/**
 * 弹窗相关
 */
const open = ref(false);
/**
 * 弹窗标题
 */
const title = ref("");
/**
 * 表单引用
 */
const formRef = ref<FormInstance>();
/**
 * 定义表单数据
 */
const form = reactive<any>({
  postName: "",
  postCode: "",
  postSort: 0,
  status: "0",
  remark: ""
});
/**
 * 表单验证规则
 */
const rules = reactive<FormRules>({
  postName: [
    { required: true, message: "请输入岗位名称", trigger: "blur" },
    { min: 2, max: 20, message: "长度在 2 到 20 个字符", trigger: "blur" }
  ],
  postCode: [
    { required: true, message: "请输入岗位编码", trigger: "blur" },
    { min: 2, max: 20, message: "长度在 2 到 20 个字符", trigger: "blur" }
  ],
  postSort: [
    { required: true, message: "请输入岗位顺序", trigger: "blur" },
    { type: "number", message: "请输入数字", trigger: "blur" }
  ],
  status: [{ required: true, message: "请选择岗位状态", trigger: "change" }]
});

/**
 * 新增岗位接口
 */
const addPost = async () => {
  try {
    const res = await addPostApi(form);
    if (res.code === 200) {
      ElMessage.success("新增成功");
      open.value = false;
      formRef.value?.resetFields();
      getPostList();
    } else {
      ElMessage.error(res.message);
    }
  } catch (error) {
    console.error(error);
  }
};

/**
 * 修改岗位接口
 */
const updatePost = async () => {
  try {
    const res = await updatePostApi(form);
    if (res.code === 200) {
      ElMessage.success("修改成功");
      open.value = false;
      formRef.value?.resetFields();
      getPostList();
    } else {
      ElMessage.error(res.message);
    }
  } catch (error) {
    console.error(error);
  }
};

/**
 * 提交表单
 * 取消表单
 */
const submitForm = () => {
  if (!formRef.value) return;
  formRef.value.validate(async (valid: boolean) => {
    if (!valid) return;
    if (form.postId) {
      updatePost();
    } else {
      addPost();
    }
  });
};

/**
 * 取消弹窗
 */
const cancel = () => {
  open.value = false;
  formRef.value!.resetFields();
  Object.assign(form, {});
};

/**
 * 获取岗位列表
 */
const getPostList = async () => {
  try {
    loading.value = true;
    const res = await getPostListApi(queryParams);
    if (res.code === 200) {
      postList.value = res.data;
      total.value = res.total!;
    } else {
      console.error(res.message);
    }
  } catch (error) {
    console.error(error);
  } finally {
    loading.value = false;
  }
};

/**
 * 组件挂载时获取岗位列表
 */
onMounted(() => {
  getPostList();
});
</script>

<style lang="scss" scoped>
.dialog-footer {
  text-align: right;
}
</style>
